// 用户模块
import { userAccountLogin, userQQPatchLogin, userQQBindLogin, userQQLogin } from '@/api/user.js'

export default {
  namespaced: true,
  state: {
    uname: 'lisi',
    profile: {
      id: '',
      avatar: '',
      nickname: '',
      account: '',
      mobile: '',
      token: ''
    }
  },
  mutations: {
    updateUname (state, payload) {
      state.uname = payload
    },
    updateUserInfo (state, payload) {
      // 更新用户信息
      state.profile = payload
    }
  },
  actions: {
    // QQ直接登录
    async qqLogin (context, unionId) {
      try {
        const ret = await userQQLogin(unionId)
        if (ret.result) {
        // 登录成功
          const { id, avatar, nickname, account, mobile, token } = ret.result
          context.commit('updateUserInfo', { id, avatar, nickname, account, mobile, token })
          return true
        } else {
        // 登录失败
          return false
        }
      } catch {
        return false
      }
    },
    // 绑定手机号
    async bindMobile (context, payload) {
      try {
        const ret = await userQQBindLogin(payload.unionId, payload.mobile, payload.code)
        if (ret.result) {
        // 登录成功
          const { id, avatar, nickname, account, mobile, token } = ret.result
          context.commit('updateUserInfo', { id, avatar, nickname, account, mobile, token })
          return true
        } else {
        // 登录失败
          return false
        }
      } catch {
        return false
      }
    },
    // 注册账号
    async registerAccount (context, payload) {
      try {
        const ret = await userQQPatchLogin(payload.unionId, payload.form)
        if (ret.result) {
        // 登录成功
          const { id, avatar, nickname, account, mobile, token } = ret.result
          context.commit('updateUserInfo', { id, avatar, nickname, account, mobile, token })
          return true
        } else {
        // 登录失败
          return false
        }
      } catch {
        return false
      }
    },
    // 基于账号的登录
    async accountLogin (context, payload) {
      // 调用接口实现登录
      try {
        const ret = await userAccountLogin(payload)
        if (ret.result) {
        // 登录成功
          const { id, avatar, nickname, account, mobile, token } = ret.result
          context.commit('updateUserInfo', { id, avatar, nickname, account, mobile, token })
          return true
        } else {
        // 登录失败
          return false
        }
      } catch {
        return false
      }
    }
  },
  getters: {}
}
